package com.pac.questionnaire.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.common.tools.SmsTools;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.pac.doctor.DoctorKeyContent;
import com.pac.doctor.bean.DoctorBean;
import com.pac.doctor.service.DoctorService;
import com.pac.file.bean.FileBean;
import com.pac.file.service.FileService;
import com.pac.questionnaire.QuestionnaireKeyContent;
import com.pac.questionnaire.bean.QuestionnaireAnswerBean;
import com.pac.questionnaire.bean.QuestionnaireAnswerFileBean;
import com.pac.questionnaire.bean.QuestionnaireBean;
import com.pac.questionnaire.bean.QuestionnaireDiagnosisAutoBean;
import com.pac.questionnaire.bean.QuestionnaireDiagnosisBean;
import com.pac.questionnaire.dao.QuestionnaireDiagnosisDao;
import com.pac.questionnaire.service.QuestionnaireAnswerFileService;
import com.pac.questionnaire.service.QuestionnaireAnswerService;
import com.pac.questionnaire.service.QuestionnaireDiagnosisAutoService;
import com.pac.questionnaire.service.QuestionnaireDiagnosisService;
import com.pac.questionnaire.service.QuestionnaireService;
import com.pac.user.UserKeyContent;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.service.UserDetailService;
import com.pac.weixin.WeiXinKeyContent;
import com.pac.weixin.bean.WxChatAutoBean;
import com.pac.weixin.bean.WxChatBean;
import com.pac.weixin.bean.WxDoctorSelBean;
import com.pac.weixin.service.WxChatAutoService;
import com.pac.weixin.service.WxChatService;
import com.pac.weixin.service.WxDoctorSelService;

/**
 * 问卷回答Service实现
 * 
 * @author lujun.chen
 * @version [版本号, 2015年3月9日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service(value = "questionnaireDiagnosisService")
public class QuestionnaireDiagnosisServiceImpl implements
		QuestionnaireDiagnosisService {

	private static Logger logger = Logger
			.getLogger(QuestionnaireDiagnosisService.class);

	@Autowired
	private QuestionnaireDiagnosisDao questionnaireDiagnosisDao;

	@Autowired
	private WxDoctorSelService wxDoctorSelService;

	@Autowired
	private QuestionnaireAnswerService questionnaireAnswerService;

	@Autowired
	private WxChatService wxChatService;

	@Autowired
	private WxChatAutoService wxChatAutoService;

	@Autowired
	private DoctorService doctorService;

	@Autowired
	private QuestionnaireService questionnaireService;

	@Autowired
	private QuestionnaireDiagnosisAutoService questionnaireDiagnosisAutoService;

	@Autowired
	private QuestionnaireAnswerFileService questionnaireAnswerFileService;

	@Autowired
	private FileService fileService;

	@Autowired
	private UserDetailService userDetailService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String addQuestionnaireDiagnosis(
			QuestionnaireDiagnosisBean questionnaireDiagnosisBean) {
		if (null == questionnaireDiagnosisBean) {
			logger.error("添加问卷回答出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(questionnaireDiagnosisBean.getQuestionnaireId())) {
			logger.error("添加问卷回答出错，问卷ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "问卷ID为空");
		}

		if (StringTools.isNull(questionnaireDiagnosisBean.getDoctorUserId())) {
			logger.error("添加问卷回答出错，医生用户ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "医生用户ID为空");
		}

		// 用户全局Id通过微信openid去获取
		questionnaireDiagnosisBean
				.setState(QuestionnaireKeyContent.QUESTIONNAIRE_DIAGNOSIS_STATE_NORMAL);
		String diagnosisId = questionnaireDiagnosisDao
				.addQuestionnaireDiagnosis(questionnaireDiagnosisBean);

		return diagnosisId;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateQuestionnaireDiagnosis(
			QuestionnaireDiagnosisBean questionnaireDiagnosisBean) {
		if (null == questionnaireDiagnosisBean) {
			logger.error("更新问卷回答出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(questionnaireDiagnosisBean.getId())) {
			logger.error("更新问卷问题出错，答卷ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "答卷ID为空");
		}

		return questionnaireDiagnosisDao
				.updateQuestionnaireDiagnosis(questionnaireDiagnosisBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean delQuestionnaireDiagnosis(
			QuestionnaireDiagnosisBean questionnaireDiagnosisBean) {

		if (null == questionnaireDiagnosisBean) {
			logger.error("删除答卷出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(questionnaireDiagnosisBean.getId())) {
			logger.error("删除答卷出错，答卷ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "答卷ID为空");
		}

		return questionnaireDiagnosisDao
				.delQuestionnaireDiagnosis(questionnaireDiagnosisBean);
	}

	@Override
	public List<QuestionnaireDiagnosisBean> queryQuestionnaireDiagnosis(
			QuestionnaireDiagnosisBean questionnaireDiagnosisBean) {

		if (null != questionnaireDiagnosisBean) {
			// 病史，默认查询当天的
			if (QuestionnaireKeyContent.QUESTIONNAIRE_TYPE_MEDICAL_HISTORY
					.equals(questionnaireDiagnosisBean.getQuestionnaireType())) {
				if (StringTools.isNull(questionnaireDiagnosisBean
						.getAnswerDateStart())) {
					String answerDateStart = TimeTools.now("yyyy-MM-dd")
							+ " 00:00:00";
					questionnaireDiagnosisBean
							.setAnswerDateStart(answerDateStart);
				}
				questionnaireDiagnosisBean
						.setAutoSend(QuestionnaireKeyContent.QUESTIONNAIRE_AUTO_SEND_NO);

			} else if (QuestionnaireKeyContent.QUESTIONNAIRE_TYPE_FOLLOW_UP
					.equals(questionnaireDiagnosisBean.getQuestionnaireType())) {
				questionnaireDiagnosisBean
						.setAutoSend(QuestionnaireKeyContent.QUESTIONNAIRE_AUTO_SEND_YES);
			} else if (QuestionnaireKeyContent.QUESTIONNAIRE_TYPE_OBSERVE
					.equals(questionnaireDiagnosisBean.getQuestionnaireType())) {
				String questionnaireIds = "54";
				questionnaireDiagnosisBean.setQuestionnaireId(questionnaireIds);
			}

		}

		return questionnaireDiagnosisDao
				.queryQuestionnaireDiagnosis(questionnaireDiagnosisBean);
	}

	@Override
	public QuestionnaireDiagnosisBean findQuestionnaireDiagnosis(
			QuestionnaireDiagnosisBean questionnaireDiagnosisBean) {
		if (null == questionnaireDiagnosisBean) {
			return null;
		}

		List<QuestionnaireDiagnosisBean> diagnosis = questionnaireDiagnosisDao
				.queryQuestionnaireDiagnosis(questionnaireDiagnosisBean);
		if (null != diagnosis && diagnosis.size() > 0) {
			return diagnosis.get(0);
		}

		return null;
	}

	/** 微信用户回答问卷 */

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Map<String, String> answerQuestionnaire(String openid,
			String questionnaireId, Map<String, Object[]> answers,
			Map<String, List<MultipartFile>> filesMap, Map<String, String> param) {

		// 1、保存答卷

		// 1.2根据微信openid获取用户当前选择的医生
		WxDoctorSelBean wxDoctorSelBean = wxDoctorSelService
				.findWxDoctorSelByOpenid(openid);
		if (!QuestionnaireKeyContent.QUESTIONNAIRE_ID_M6
				.equals(questionnaireId)) {
			if (null == wxDoctorSelBean) {
				logger.error("微信用户【" + openid + "】当前未成功选择医生，请重新选择");
				throw new LogicException(ErrorNumber.ERROR_MESSAGE, "微信用户【"
						+ openid + "】当前未成功选择医生，请重新选择");
			}
		} else {
			if (null == wxDoctorSelBean) {
				wxDoctorSelBean = new WxDoctorSelBean();
				wxDoctorSelBean
						.setUserId(DoctorKeyContent.DOCTOR_CHONGYI_USER_ID);
				wxDoctorSelBean.setOpenId(openid);
				try {
					wxDoctorSelService.addWxDoctorSel(wxDoctorSelBean);
				} catch (Exception ex) {
					logger.error("填写微信用户和医生关联关系出错，" + ex);
				}
			}
		}

		// 获取医生姓名
		DoctorBean doctorBean = new DoctorBean();
		doctorBean.setUserId(wxDoctorSelBean.getUserId());
		DoctorBean doctorR = doctorService.findDoctor(doctorBean);
		String doctorName = "";
		if (null != doctorR) {
			doctorName = doctorR.getName();
		}

		// 获取患者信息
		// 获取患者姓名
		UserDetailBean userDetail = userDetailService
				.findUserDetailByOpenId(openid);
		String patientName = "";
		if (null != userDetail) {
			patientName = userDetail.getName();
		}

		// 获取问卷信息
		QuestionnaireBean questionnaireBean = new QuestionnaireBean();
		questionnaireBean.setId(questionnaireId);
		questionnaireBean = questionnaireService
				.findQuestionnaire(questionnaireBean);

		String batchNo = param.get("batchNo");

		QuestionnaireDiagnosisBean questionnaireDiagnosisBean = new QuestionnaireDiagnosisBean();
		questionnaireDiagnosisBean.setOpenId(openid);
		questionnaireDiagnosisBean.setQuestionnaireId(questionnaireId);
		questionnaireDiagnosisBean.setDoctorUserId(wxDoctorSelBean.getUserId());
		questionnaireDiagnosisBean.setAnswerDate(TimeTools.now());
		questionnaireDiagnosisBean.setDoctorName(doctorName);
		questionnaireDiagnosisBean.setPatientName(patientName);
		questionnaireDiagnosisBean
				.setState(QuestionnaireKeyContent.QUESTIONNAIRE_DIAGNOSIS_STATE_NORMAL);
		questionnaireDiagnosisBean.setBatchNo(batchNo);
		String answerId = questionnaireDiagnosisDao
				.addQuestionnaireDiagnosis(questionnaireDiagnosisBean);

		// 2、保存答卷答案
		// keySet由三部分组成，question_问题ID_问题类型
		Map<Integer, Integer> answerMap = new TreeMap<Integer, Integer>();
		Set<String> questions = answers.keySet();
		for (String question : questions) {
			String[] ans = (String[]) answers.get(question);
			for (String answer : ans) {

				if (StringTools.isNull(answer)) {
					continue;
				}

				String[] questionsp = question.split("_");
				String questionId = questionsp[1];// 问题ID
				String questionType = questionsp[2];// 问题类型

				QuestionnaireAnswerBean questionnaireAnswerBean = new QuestionnaireAnswerBean();
				questionnaireAnswerBean.setQuestionnaireId(questionnaireId);
				questionnaireAnswerBean.setQuestionId(questionId);
				questionnaireAnswerBean.setAnswerId(answerId);
				questionnaireAnswerBean.setCreateDate(TimeTools.now());
				questionnaireAnswerBean
						.setHasFile(QuestionnaireKeyContent.QUESTION_HAS_FILE_NO);

				// 选择题
				if (QuestionnaireKeyContent.QUESTION_TYPE_SINGLE_SELECT
						.equals(questionType)
						|| QuestionnaireKeyContent.QUESTION_TYPE_MULTI_SELECT
								.equals(questionType)) {
					questionnaireAnswerBean.setOptionId(answer);
					answerMap.put(Integer.valueOf(questionId),
							Integer.valueOf(answer));

				}
				// 问答题
				else if (QuestionnaireKeyContent.QUESTION_TYPE_INTERLOCUTION
						.equals(questionType)) {
					questionnaireAnswerBean.setAnswer(answer);
				}
				questionnaireAnswerService
						.addQuestionnaireAnswer(questionnaireAnswerBean);
			}

		}

		// 3、保存答卷答案对应的附件
		Set<String> fileKeys = filesMap.keySet();
		String filePath = "questionnaire";
		for (String fileKey : fileKeys) {
			List<MultipartFile> fileList = filesMap.get(fileKey);
			for (MultipartFile multipartFile : fileList) {
				try {

					if (multipartFile.getSize() > 0) {
						FileBean fileBean = fileService.uploadMultipartFile(
								multipartFile, filePath);

						QuestionnaireAnswerFileBean answerFile = new QuestionnaireAnswerFileBean();
						answerFile.setFileId(fileBean.getId());
						answerFile.setDiagnosisId(answerId);
						answerFile.setPath(fileBean.getPath());
						String questionId = fileKey.split("_")[2];
						answerFile.setQuestionId(questionId);
						questionnaireAnswerFileService
								.addQuestionnaireAnswerFile(answerFile);
					}

				} catch (LogicException ex) {
					logger.error("回答问卷，上传附件保存出错，" + ex.getMessage());
				} catch (Exception ex) {
					logger.error("回答问卷，上传附件保存出错，" + ex);
				}
			}
		}

		// 只有病史需要回访
		// 重医附二院模板
		String diagnosis = "感谢您的作答";
		if (QuestionnaireKeyContent.QUESTIONNAIRE_ID_RETURN_VIEW
				.equals(questionnaireId)) {
			customQuestionnaire(openid, questionnaireId, answerId, patientName,
					wxDoctorSelBean.getUserId());

			questionnaireDiagnosisBean.setId(answerId);
			questionnaireDiagnosisBean.setBatchNo(answerId);
			questionnaireDiagnosisDao
					.updateQuestionnaireDiagnosis(questionnaireDiagnosisBean);
		}
		// 医院定制化问卷
		else if (QuestionnaireKeyContent.QUESTIONNAIRE_AUTO_SEND_NO
				.equals(questionnaireBean.getAutoSend())
				&& (!QuestionnaireKeyContent.QUESTIONNAIRE_ID_RETURN_VIEW
						.equals(questionnaireId))) {
			String hospitalId = doctorR.getHospitalId();
			generalQuestionnaire(openid, questionnaireId, answerId,
					wxDoctorSelBean.getUserId(), hospitalId, patientName);

			questionnaireDiagnosisBean.setId(answerId);
			questionnaireDiagnosisBean.setBatchNo(answerId);
			questionnaireDiagnosisDao
					.updateQuestionnaireDiagnosis(questionnaireDiagnosisBean);
		}

		// 7、问卷自动回复，获取回复内容
		if (QuestionnaireKeyContent.QUESTION_AUTO_ANSWER_YES
				.equals(questionnaireBean.getAutoAnswer())) {
			StringBuffer sbAnswer = new StringBuffer();// 查询自动回复回答
			Set<Integer> questionIds = answerMap.keySet();
			for (Integer questionid : questionIds) {
				sbAnswer.append(questionid + "_" + answerMap.get(questionid)
						+ "~");
			}
			String answerStr = sbAnswer.toString();
			answerStr = answerStr.substring(0, answerStr.length() - 1);
			logger.debug("answerstr:" + answerStr);
			QuestionnaireDiagnosisAutoBean diagnosisAuto = questionnaireDiagnosisAutoService
					.findQuestionnaireDiagnosisAutoByAnser(answerStr);
			if (null != diagnosisAuto) {
				diagnosis = diagnosisAuto.getDiagnosis();
			} else {
				diagnosis = "感谢您的作答";
			}

			// 自动作为诊疗记录保存
			QuestionnaireDiagnosisBean diagnosisE = new QuestionnaireDiagnosisBean();
			diagnosisE.setId(answerId);
			diagnosisE.setDiagnosis(diagnosis);
			diagnosisE.setDiagnosisDate(TimeTools.now());
			questionnaireDiagnosisDao.updateQuestionnaireDiagnosis(diagnosisE);

			// 自动回复内容发到手机微信聊天窗口
			WxChatBean chatToWxUser = new WxChatBean();
			chatToWxUser.setContent(diagnosis);
			chatToWxUser.setOpenId(openid);
			chatToWxUser.setUserId(wxDoctorSelBean.getUserId());
			wxChatService.addChatFromPac(chatToWxUser);
		}

		// 8、回答临床观察表，用信息中临床观察表状态填写状态改为已填
		if (QuestionnaireKeyContent.QUESTIONNAIRE_ID_OBSERVE
				.equals(questionnaireId)) {
			UserDetailBean userDetailBean = new UserDetailBean();
			userDetailBean.setObserve(UserKeyContent.USER_WX_OBSERVE_ACHIEVE);
			userDetailBean.setOpenId(openid);
			userDetailBean.setQuestionnaireId(questionnaireId);
			userDetailService.updateUserDetail(userDetailBean);
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("answerId", answerId);
		map.put("diagnosis", diagnosis);

		return map;
	}

	/**
	 * 问卷通用逻辑
	 * 
	 * @param openid
	 *            患者微信openId
	 * @param questionnaireId
	 *            病史问卷ID（不自动推送的问卷）
	 * @param answerId
	 *            答卷ID
	 * @param doctorUserId
	 *            医师ID
	 * @param hospitalId
	 *            医生所属医院ID
	 * @see [类、类#方法、类#成员]
	 */
	public void generalQuestionnaire(String openid, String questionnaireId,
			String answerId, String doctorUserId, String hospitalId,
			String patientName) {

		// 获取医院下自动推送的问题
		QuestionnaireBean questionnaireQ = new QuestionnaireBean();
		questionnaireQ.setHospitalId(hospitalId);
		questionnaireQ
				.setAutoSend(QuestionnaireKeyContent.QUESTIONNAIRE_AUTO_SEND_YES);
		List<QuestionnaireBean> questionnaireList = questionnaireService
				.queryQuestionnaire(questionnaireQ);
		if ((null != questionnaireList) && (!questionnaireList.isEmpty())) {
			String domain = PropertyUtils.getValue("system.domain.url");
			for (QuestionnaireBean questionnaireR : questionnaireList) {

				String urlL1 = domain
						+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire&openId="
						+ openid + "&qusetionnaireId=" + questionnaireR.getId();
				String sendCycleVal = questionnaireR.getSendCycleVal();
				String sendCycleName = "月";
				if (QuestionnaireKeyContent.SEND_CYCLE_DAY
						.equals(questionnaireR.getSendCycle())) {
					sendCycleName = "天";
				} else if (QuestionnaireKeyContent.SEND_CYCLE_MONTH
						.equals(questionnaireR.getSendCycle())) {
					sendCycleName = "月";
				} else if (QuestionnaireKeyContent.SEND_CYCLE_WEEK
						.equals(questionnaireR.getSendCycle())) {
					sendCycleName = "周";
				} else if (QuestionnaireKeyContent.SEND_CYCLE_YEAR
						.equals(questionnaireR.getSendCycle())) {
					sendCycleName = "年";
				}
				StringBuffer oneMonthSb = new StringBuffer();
				oneMonthSb.append("据您小产已经");
				oneMonthSb.append(sendCycleVal);
				oneMonthSb.append(sendCycleName);
				oneMonthSb.append("了，康复情况如何？请完成如下随访表：");
				oneMonthSb.append("<a href='");
				oneMonthSb.append(urlL1);
				oneMonthSb.append("'>");
				oneMonthSb.append(questionnaireR.getTitle());
				oneMonthSb.append("</a>");
				WxChatAutoBean wxChatAutoBean = new WxChatAutoBean();
				wxChatAutoBean.setOpenId(openid);
				wxChatAutoBean.setUserId(doctorUserId);
				wxChatAutoBean.setContent(oneMonthSb.toString());
				GregorianCalendar gc = new GregorianCalendar();
				Date d = new Date();
				gc.setTime(d);
				Integer sendCycleValInt = Integer.valueOf(sendCycleVal);
				if (QuestionnaireKeyContent.SEND_CYCLE_DAY
						.equals(questionnaireR.getSendCycle())) {
					gc.add(Calendar.DATE, sendCycleValInt);
				} else if (QuestionnaireKeyContent.SEND_CYCLE_MONTH
						.equals(questionnaireR.getSendCycle())) {
					gc.add(Calendar.MONTH, sendCycleValInt);
				} else if (QuestionnaireKeyContent.SEND_CYCLE_WEEK
						.equals(questionnaireR.getSendCycle())) {
					gc.add(Calendar.DATE, sendCycleValInt
							* Calendar.DAY_OF_WEEK);
				} else if (QuestionnaireKeyContent.SEND_CYCLE_YEAR
						.equals(questionnaireR.getSendCycle())) {
					gc.add(Calendar.YEAR, sendCycleValInt);
				}

				StringBuffer sbTemplateContent = new StringBuffer();
				sbTemplateContent.append("据您小产已经");
				sbTemplateContent.append(sendCycleVal);
				sbTemplateContent.append(sendCycleName);
				sbTemplateContent.append("了，");
				sbTemplateContent.append("康复情况如何？点击详情完成随访表,以便医生了解您的康复情况。");
				String sendDate = TimeTools.getDateFormat(gc.getTime(),
						TimeTools.DATE_FORMAT_DEFAULT);
				wxChatAutoBean.setSendDate(sendDate);
				wxChatAutoBean.setPatient(patientName);
				wxChatAutoBean.setTemplateContent(sbTemplateContent.toString());
				wxChatAutoBean.setTemplateTitle(questionnaireR.getTitle());
				wxChatAutoBean.setTemplateUrl(urlL1);
				wxChatAutoService.addWxChatAuto(wxChatAutoBean);

			}
		}

		// 病史后续
		medicalHistoryAnswer(openid, answerId, doctorUserId, questionnaireId);
	}

	/**
	 * 重医附二院推送问卷模板
	 * 
	 * @param openid
	 *            患者微信openid
	 * @param questionnaireId
	 *            问卷ID
	 * @param answerId
	 *            答案ID
	 * @param patientName
	 *            患者姓名
	 * @param doctorUserId
	 *            医生ID
	 * @see [类、类#方法、类#成员]
	 */
	private void customQuestionnaire(String openid, String questionnaireId,
			String answerId, String patientName, String doctorUserId) {
		// 4、告知医生有问卷过来了，需要诊断
		StringBuffer sb = new StringBuffer();
		sb.append("病史已经提交，");
		String domain = PropertyUtils.getValue("system.domain.url");
		sb.append("<a href=\"javascript:openWinQuestionnaireDiagnosis('");
		sb.append(domain);
		sb.append("/questionnaire/gotoPage?pageName=");
		sb.append("answer_questionnaire_");
		sb.append(questionnaireId);
		sb.append("&");
		sb.append("answer_id");
		sb.append("=");
		sb.append(answerId);
		sb.append("&");
		sb.append("questionnaireId");
		sb.append("=");
		sb.append(questionnaireId);
		sb.append("','");
		sb.append(answerId);
		sb.append("')\",>");
		sb.append("病史");
		sb.append("</a>");
		WxChatBean wxChatBean = new WxChatBean();
		wxChatBean.setContent(sb.toString());
		wxChatBean.setCreateDate(TimeTools.now());
		wxChatBean.setDirection(WeiXinKeyContent.WEIXIN_CHAT_DIRECTION_WX_PAC);
		wxChatBean.setOpenId(openid);
		wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_NO);
		wxChatBean.setUserId(doctorUserId);
		wxChatService.addWxChat(wxChatBean);

		// 5.1、一个月后回访通知【康复情况】
		String urlL1 = domain
				+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire49&openId="
				+ openid + "&batchNo=" + answerId;
		StringBuffer oneMonthSb = new StringBuffer();
		oneMonthSb.append("据您小产已经一个月了，康复情况如何？请完成如下随访表：");
		oneMonthSb.append("<a href='");
		oneMonthSb.append(urlL1);
		oneMonthSb.append("'>月经恢复情况</a>");
		WxChatAutoBean wxChatAutoBean = new WxChatAutoBean();
		wxChatAutoBean.setOpenId(openid);
		wxChatAutoBean.setUserId(doctorUserId);
		wxChatAutoBean.setContent(oneMonthSb.toString());
		GregorianCalendar gc = new GregorianCalendar();
		Date d = new Date();
		gc.setTime(d);
		gc.add(2, 1);// 加一个月+1天
		gc.add(GregorianCalendar.DAY_OF_YEAR, 1);
		String sendDate = TimeTools.getDateFormat(gc.getTime(),
				TimeTools.DATE_FORMAT_DEFAULT);
		wxChatAutoBean.setSendDate(sendDate);
		wxChatAutoBean.setPatient(patientName);
		wxChatAutoBean
				.setTemplateContent("据您小产已经一个月了，康复情况如何？点击详情完成随访表,以便医生了解您的康复情况。");
		wxChatAutoBean.setTemplateTitle("月经恢复情况");
		wxChatAutoBean.setTemplateUrl(urlL1);
		wxChatAutoService.addWxChatAuto(wxChatAutoBean);

		// 5.2、一个月后回访通知【性生活恢复和避孕情况】
		String urlL2 = domain
				+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire51&openId="
				+ openid + "&batchNo=" + answerId;
		StringBuffer oneMonthSb2 = new StringBuffer();
		oneMonthSb2.append("据您小产已经一个月了，康复情况如何？请完成如下随访表：");
		oneMonthSb2.append("<a href='");
		oneMonthSb2.append(urlL2);
		oneMonthSb2.append("'>性生活恢复和避孕情况</a>");
		WxChatAutoBean wxChatAutoBean2 = new WxChatAutoBean();
		wxChatAutoBean2.setOpenId(openid);
		wxChatAutoBean2.setUserId(doctorUserId);
		wxChatAutoBean2.setContent(oneMonthSb2.toString());
		GregorianCalendar gc2 = new GregorianCalendar();
		Date d2 = new Date();
		gc2.setTime(d2);
		gc2.add(2, 1);// 加一个月
		String sendDate2 = TimeTools.getDateFormat(gc2.getTime(),
				TimeTools.DATE_FORMAT_DEFAULT);
		wxChatAutoBean2.setSendDate(sendDate2);
		wxChatAutoBean2.setPatient(patientName);
		wxChatAutoBean2.setTemplateTitle("性生活恢复和避孕情况");
		wxChatAutoBean2
				.setTemplateContent("据您小产已经一个月了，康复情况如何？点击详情完成随访表,以便医生了解您的康复情况。");
		wxChatAutoBean2.setTemplateUrl(urlL2);
		wxChatAutoService.addWxChatAuto(wxChatAutoBean2);

		// 6、三个月后复查通知
		StringBuffer threeMonthSb = new StringBuffer();
		String url3 = domain
				+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire52&openId="
				+ openid + "&batchNo=" + answerId;
		threeMonthSb.append("温馨小提示：亲，两天后是您人流术后 3 月随访的日期，请你于来院前将“");
		threeMonthSb.append("\r\n");
		threeMonthSb.append("<a href='");
		threeMonthSb.append(url3);
		threeMonthSb.append("'>性生活恢复和避孕情况随访表</a>");
		threeMonthSb.append("”填写完毕喔。");
		threeMonthSb.append("您提供的有效信息将有助于医师对您病情的了解，请务必不要忘记填写喔。");
		threeMonthSb.append("——您的医学小秘书");

		WxChatAutoBean wxChatAuto3 = new WxChatAutoBean();
		wxChatAuto3.setContent(threeMonthSb.toString());
		wxChatAuto3.setOpenId(openid);
		wxChatAuto3.setUserId(doctorUserId);
		GregorianCalendar gc3 = new GregorianCalendar();
		Date d3 = new Date();
		gc3.setTime(d3);
		gc3.add(2, 3);// 加三个月
		String sendDate3 = TimeTools.getDateFormat(gc3.getTime(),
				TimeTools.DATE_FORMAT_DEFAULT);
		wxChatAuto3.setSendDate(sendDate3);
		wxChatAuto3.setPatient(patientName);
		wxChatAuto3.setTemplateTitle("性生活恢复和避孕情况");
		wxChatAuto3
				.setTemplateContent("据您小产已经三个月了，康复情况如何？点击详情完成随访表,以便医生了解您的康复情况。");
		wxChatAuto3.setTemplateUrl(url3);
		wxChatAutoService.addWxChatAuto(wxChatAuto3);

		// 7、六个月随访问卷
		StringBuffer sixMonthSb = new StringBuffer();
		String url6 = domain
				+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire53&openId="
				+ openid + "&batchNo=" + answerId;
		sixMonthSb.append("据您小产已经六个月了，康复情况如何？请完成如下随访表：");
		sixMonthSb.append("<a href='");
		sixMonthSb.append(url6);
		sixMonthSb.append("'>服务对象流产后6个月随访</a>");
		WxChatAutoBean wxChatAuto6 = new WxChatAutoBean();
		wxChatAuto6.setContent(sixMonthSb.toString());
		wxChatAuto6.setOpenId(openid);
		wxChatAuto6.setUserId(doctorUserId);
		GregorianCalendar gc6 = new GregorianCalendar();
		Date d6 = new Date();
		gc6.setTime(d6);
		gc6.add(2, 6);// 加六个月
		String sendDate6 = TimeTools.getDateFormat(gc6.getTime(),
				TimeTools.DATE_FORMAT_DEFAULT);
		wxChatAuto6.setSendDate(sendDate6);
		wxChatAuto6.setPatient(patientName);
		wxChatAuto6.setTemplateTitle("服务对象流产后6个月随访");
		wxChatAuto6
				.setTemplateContent("据您小产已经六个月了，康复情况如何？点击详情完成随访表,以便医生了解您的康复情况。");
		wxChatAuto6.setTemplateUrl(url6);
		wxChatAutoService.addWxChatAuto(wxChatAuto6);

		// 病史后续
		medicalHistoryAnswer(openid, answerId, doctorUserId, questionnaireId);
	}

	/**
	 * 病史回答
	 * 
	 * 1、要求上传检查结果
	 * 
	 * 2、更新患者所处阶段
	 * 
	 * @param openid
	 *            患者微信openid
	 * @param answerId
	 *            答卷ID
	 * @param doctorUserId
	 *            患者所选医师ID
	 * @param questionnaireId
	 *            问卷ID
	 * @see [类、类#方法、类#成员]
	 */
	public void medicalHistoryAnswer(String openid, String answerId,
			String doctorUserId, String questionnaireId) {

		// 5.0、告知用户问病史已经发给医生
		String domain = PropertyUtils.getValue("system.domain.url");
		WxChatBean chatToWxUser = new WxChatBean();
		String urlToUser = domain
				+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaireFile&diagnosisId="
				+ answerId + "&openid=" + openid;
		StringBuffer sbStrToUser = new StringBuffer();
		sbStrToUser.append("您的病史已经提交给医生,");
		sbStrToUser.append("请");
		sbStrToUser.append("<a href='");
		sbStrToUser.append(urlToUser);
		sbStrToUser.append("'>上传检查结果</a>");
		sbStrToUser.append("。");

		chatToWxUser.setContent(sbStrToUser.toString());
		chatToWxUser.setOpenId(openid);
		chatToWxUser.setUserId(doctorUserId);
		wxChatService.addChatFromPac(chatToWxUser);

		// 更新用户所处阶段
		UserDetailBean userDetailBean = new UserDetailBean();
		userDetailBean
				.setStage(UserKeyContent.USER_WX_STAGE_NO_INSPECTION_RESULT);
		userDetailBean.setStageDate(TimeTools.now());
		userDetailBean.setOpenId(openid);
		userDetailBean.setQuestionnaireId(questionnaireId);
		userDetailService.updateUserDetail(userDetailBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Map<String, String> questionnaireDiagnosis(
			QuestionnaireDiagnosisBean diagnosisBean) {

		if (null == diagnosisBean) {
			logger.error("问卷诊断出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(diagnosisBean.getId())) {
			logger.error("问卷诊断出错，答卷ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "答卷ID为空");
		}

		QuestionnaireDiagnosisBean diagnosisQ = new QuestionnaireDiagnosisBean();
		diagnosisQ.setId(diagnosisBean.getId());
		QuestionnaireDiagnosisBean diagnosisR = findQuestionnaireDiagnosis(diagnosisQ);
		if (null == diagnosisR) {
			logger.error("问卷诊断出错，未找到答卷：" + diagnosisBean.getId());
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "未找到答卷");
		}

		String openId = diagnosisR.getOpenId();

		// 1、添加诊断结果
		StringBuffer sbDia = new StringBuffer();
		sbDia.append("G" + diagnosisBean.getZdg());
		sbDia.append("P" + diagnosisBean.getZdp());
		sbDia.append("，");
		sbDia.append(diagnosisBean.getZdz());
		sbDia.append("+");
		sbDia.append(diagnosisBean.getZdt());
		sbDia.append("周");
		sbDia.append("，");
		sbDia.append(diagnosisBean.getZdHandle());

		diagnosisBean.setDiagnosis(sbDia.toString());
		diagnosisBean.setDiagnosisDate(TimeTools.now());

		questionnaireDiagnosisDao.updateQuestionnaireDiagnosis(diagnosisBean);

		// 2、向用户反馈诊断结果
		WxChatBean wxChatBean = new WxChatBean();
		String contentTitle = "【" + diagnosisR.getDoctorName() + "】医生：";
		String content = "根据您的病史，诊断结果如下：" + diagnosisBean.getDiagnosis();
		wxChatBean.setContent(contentTitle + content);
		wxChatBean.setUserId(diagnosisR.getDoctorUserId());
		wxChatBean.setOpenId(openId);
		wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_YES);
		wxChatService.addChatFromPac(wxChatBean);

		// 避免向微信端推送消息推送不下去，下发短信
		UserDetailBean userDetailR = userDetailService
				.findUserDetailByOpenId(openId);
		if (null != userDetailR) {
			SmsTools.sendsms(userDetailR.getMobilePhone(), content);
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("openId", openId);
		map.put("content", content);

		try {
			UserDetailBean userDetailBean = new UserDetailBean();
			userDetailBean.setOpenId(openId);
			userDetailBean.setStage(UserKeyContent.USER_WX_STAGE_DIAGNOSED);
			userDetailBean.setStageDate(TimeTools.now());
			userDetailBean.setObserve(UserKeyContent.USER_WX_OBSERVE_WILL);
			userDetailService.updateUserDetail(userDetailBean);
		} catch (Exception ex) {
			logger.error("更新用户所处阶段：已诊断，出错，" + ex);
		}

		return map;
	}

	@Override
	public boolean questionnairedIsAnswered(String openId,
			String questionnaireId) {

		if (StringTools.isNull(openId)) {
			return false;
		}

		if (StringTools.isNull(questionnaireId)) {
			return false;
		}

		// 获取用户当前选择的医生
		WxDoctorSelBean doctorSelR = wxDoctorSelService
				.findWxDoctorSelByOpenid(openId);
		if (null == doctorSelR) {
			return false;
		}

		// 15天内不允许重复提交病史
		QuestionnaireDiagnosisBean diagnosisQ = new QuestionnaireDiagnosisBean();
		diagnosisQ.setOpenId(openId);
		diagnosisQ.setQuestionnaireId(questionnaireId);
		diagnosisQ.setDoctorUserId(doctorSelR.getUserId());
		Date d = new Date();
		String answerDateStart = TimeTools.getDateFormat(new Date(d.getTime()
				- 15 * 24 * 60 * 60 * 1000), TimeTools.DATE_FORMAT_DEFAULT);
		diagnosisQ.setAnswerDateStart(answerDateStart);
		QuestionnaireDiagnosisBean diagnosisR = this
				.findQuestionnaireDiagnosis(diagnosisQ);

		if (null == diagnosisR) {
			return false;
		}

		return true;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean addQuestionnaireFile(MultipartFile[] fileList,
			String diagnosisId, String openid) {

		String filePath = "questionnaire";
		for (MultipartFile multipartFile : fileList) {
			try {
				if (!multipartFile.isEmpty()) {
					FileBean fileBean = fileService.uploadMultipartFile(
							multipartFile, filePath);

					QuestionnaireAnswerFileBean answerFile = new QuestionnaireAnswerFileBean();
					answerFile.setFileId(fileBean.getId());
					answerFile.setDiagnosisId(diagnosisId);
					answerFile.setPath(fileBean.getPath());
					questionnaireAnswerFileService
							.addQuestionnaireAnswerFile(answerFile);
				}

			} catch (LogicException ex) {
				logger.error("回答问卷，上传附件保存出错，" + ex.getMessage());
				throw new LogicException(ErrorNumber.LOGIC_EXCEPTION,
						ex.getMessage());
			} catch (Exception ex) {
				logger.error("回答问卷，上传附件保存出错，" + ex);
				throw new LogicException(ErrorNumber.PARAM_IS_NULL, "系统内错误");
			}
		}

		// 向用户发送文件上传处理结果
		WxChatBean wxChatBean = new WxChatBean();
		String content = "您的检查结果已经成功提交给医生";
		wxChatBean.setContent(content);
		wxChatBean.setUserId(UserKeyContent.USER_ID_SYSTEM);
		wxChatBean.setOpenId(openid);
		wxChatBean.setState(WeiXinKeyContent.WEIXIN_CHAT_STATE_READ_YES);
		wxChatService.addChatFromPac(wxChatBean);

		try {

			// 更新用户所处阶段
			UserDetailBean userDetailBean = new UserDetailBean();
			userDetailBean.setOpenId(openid);
			userDetailBean.setStage(UserKeyContent.USER_WX_STAGE_NO_DIAGNOSE);
			userDetailBean.setStageDate(TimeTools.now());
			userDetailService.updateUserDetail(userDetailBean);
		} catch (Exception ex) {
			logger.error("更新用户为已上传检查结果阶段出错，" + ex);
		}

		return true;
	}

}
